package com.mixsmart.spellsql.where;

import com.mixsmart.spellsql.IExpression;
import com.mixsmart.spellsql.IWhere;
import com.mixsmart.utils.StringUtils;

/**
 * OR实现类
 * @author 乌草坡
 * @since 1.0
 */
public class OrWhere extends CompositeWhere {

	private IWhere where;

	private IWhere exp;
	
	public OrWhere(IWhere where, IWhere exp) {
		this.where = where;
		this.exp = exp;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public String build() {
		handleSameFieldVarName();
		String conditionStr = where.build() + " or " + exp.build();
		super.addParameter(where, exp);
		return conditionStr;
	}

	/**
	 * 处理相同字段的变量名;当对同一字段进行条件过滤时，
	 * 则字段对于的变量名称会加下标，从1开始
	 */
	protected void handleSameFieldVarName() {
		if(where instanceof IExpression && exp instanceof IExpression) {
			IExpression leftExp = (IExpression)where;
			IExpression rightExp = (IExpression)exp;
			String leftFieldName = leftExp.getFieldName();
			String rightFieldName = rightExp.getFieldName();
			if(leftFieldName.equals(rightFieldName)) {
				String leftFieldVarName = leftExp.getFieldVarName();
				Integer num = getSuffixNum(leftFieldVarName);
				if(null == num) {
					num = 0;
				}
				++num;
				String rightFieldVarName = rightExp.getFieldName() + num;
				rightExp.setFieldVarName(rightFieldVarName);
			}
		}
	}

	/**
	 * 返回变量后缀中的整数
	 * @param fieldVarName
	 * @return
	 */
	private Integer getSuffixNum(String fieldVarName) {
		if(StringUtils.isEmpty(fieldVarName)) {
			return null;
		}
		StringBuilder numBuilder = new StringBuilder();
		for(int i = fieldVarName.length() - 1; i > 0; i++) {
			if(Character.isDigit(fieldVarName.charAt(i))) {
				numBuilder.insert(0, fieldVarName.charAt(i));
			} else {
				break;
			}
		}
		if(numBuilder.length() > 0) {
			return Integer.parseInt(numBuilder.toString());
		} else {
			return null;
		}
	}

}
